import { createRoot } from 'react-dom/client'
import { Layout } from './layout'
import { AdminLayout } from './adminLayout'
export const renderPage = (Page: React.FC<{}>, path?: string) => {
    const nger = !!Reflect.get(window, "NGER")
    const container = document.getElementById('app');
    const outlet = Reflect.get(window, 'ROUTER_OUTLET') || container;
    const root = Reflect.get(window, 'REACT_ROOT') || createRoot(outlet!, {
        identifierPrefix: `${new Date().getTime()}`
    });
    if (path) {
        get(path.split('/').filter(it => !!it), window, () => {
            return <Layout>
                <Page />
            </Layout>
        })
    }
    if (!nger) {
        root.render(<Layout>
            <Page />
        </Layout>)
    }
}
export const renderAdminPage = (Page: React.FC<{}>, path?: string) => {
    const nger = !!Reflect.get(window, "NGER")
    const container = document.getElementById('app');
    const outlet = Reflect.get(window, 'ROUTER_OUTLET') || container;
    const root = Reflect.get(window, 'REACT_ROOT') || createRoot(outlet!, {
        identifierPrefix: `${new Date().getTime()}`
    });
    if (path) {
        get(path.split('/').filter(it => !!it), window, () => {
            return () => <Layout>
                <Page />
            </Layout>
        })
    }
    if (!nger) {
        root.render(<AdminLayout>
            <Page />
        </AdminLayout>)
    }
}

function get(paths: string[], val: any, render: Function) {
    if (paths.length <= 0) {
        return val
    };
    const [path, ...other] = paths;
    const has = Reflect.has(val, path)
    if (has) {
        return get(other, Reflect.get(val, path), render)
    } else {
        if (other && other.length > 0) {
            const res = {}
            Reflect.set(val, path, res)
            return get(other, res, render)
        } else {
            const res = { render }
            Reflect.set(val, path, res)
            return get(other, res, render)
        }
    }
}